package com.example.goodsmanagementcabinet.finger;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

import com.example.goodsmanagementcabinet.base.GoodBoxManagerApp_;
import com.example.goodsmanagementcabinet.otto.OttoManager;
import com.example.goodsmanagementcabinet.otto.OttoMsg;
import com.example.goodsmanagementcabinet.speaker.Speaker_;
import com.wellcom.finger.FpDriverICBC;

public class FingerHandler {
    public static FingerHandler fingerHandler;
    public String sRandom = "MTExMTExMTE=";    //  12345678
    public static final String sBmpFile = Environment.getExternalStorageDirectory() + "/icbc_finger.bmp";
    public static boolean g_bIsCancel = false;
    FpDriverICBC mIFpDevDriver;
    String sDeviceID = "01-J11111112";
    public boolean isOpen = false;
    String tz;

    public static FingerHandler getInstance() {
        if (fingerHandler == null) {
            fingerHandler = new FingerHandler();
        }
        return fingerHandler;
    }

    //打开指纹连接
    public void open(Context context, Handler mhandler) {
        try {
            mIFpDevDriver = new FpDriverICBC(context, mhandler);// finger print driver
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String[] arrRet;
        arrRet = mIFpDevDriver.openDevice();
        e("arrRet:" + arrRet[1]);
        if (arrRet[0].equals("0")) {
            // 获取设备ID
            e("连接成功");
            arrRet = mIFpDevDriver.getDeviceID();
            if (arrRet[0].equals("0")) {
                sDeviceID = arrRet[1];
                isOpen = true;
                e("DeviceId:" + sDeviceID);
            } else {
                e("arrRet1:" + arrRet[1]);
            }
        }
    }

    public void cancel() {
        mIFpDevDriver.Cancel();
        g_bIsCancel = true;
    }

    //关闭连接
    public void close() {
        g_bIsCancel = true;
        mIFpDevDriver.closeDevice();
        mIFpDevDriver = null;
        fingerHandler = null;
    }

    private static final int IMAGE_LEN_BASE64 = ((152 * 201) * 4 / 3 + 3);

    public void collect() {
        g_bIsCancel = false;
        if (isOpen) {
            String sImage1 = "";
            String sImage2 = "";
            String sImage3 = "";
            byte[] szCurImageBuf = new byte[IMAGE_LEN_BASE64];
            int iIsValid = -1;
            int iCount = 0, isOK = -1;
            int iTimeOut = 0;
            int dwImageLen = 0;
            long lStartTime, lEndTime;
            String[] arrRet;

            if (sDeviceID.equals("")) {
                speak("未获取设备ID");
                return;
            }

            // 循环采集指纹图像，采集到合格的三幅指纹图像
            // 循环采集指纹图像，采集到合格的三幅指纹图像
            lStartTime = System.currentTimeMillis();
            iTimeOut = 45;
            speak("请按手指");
            while (true) {
                // 检测手指是否按下 (可以通过FPICheckFinger来检测是否按手指，然后再采集图像)
                // 是否取消
                if (g_bIsCancel) {
                    speak("操作取消");
                    return;
                }

                if (iCount == 1) {
                    speak("请再按一次手指");
                }

                // 采集指纹图像1
                if (iCount > 2) {
                    //Sleep(100);
                    break;
                }

                // 判定时间
                lEndTime = System.currentTimeMillis();
                if ((lEndTime - lStartTime) >= iTimeOut * 1000) {
                    speak("操作超时");
                    return;
                }

                arrRet = mIFpDevDriver.checkFinger();

                if (arrRet[0].equals("0") && isOK == -1) {

                    // 取指纹图像
                    arrRet = mIFpDevDriver.getImageEx(sDeviceID, sRandom, sBmpFile);
                    if (!arrRet[0].equals("0")) {
//                        speak("采集指纹图像出错");
                        continue;
                    }
                    dwImageLen = Integer.parseInt(arrRet[2]);
                    System.arraycopy(arrRet[1].getBytes(), 0, szCurImageBuf, 0, dwImageLen);
                    isOK = 0;
                    iIsValid = 1;
                } else {
                    continue;
                }

                if (iIsValid == 1 && isOK == 0) {
                    if (iCount == 0)
                        sImage1 = new String(szCurImageBuf);
                    else if (iCount == 1)
                        sImage2 = new String(szCurImageBuf);
                    else
                        sImage3 = new String(szCurImageBuf);
                    isOK = -1;
                    iCount++;
                }

            }
            // 合成指纹特征
            arrRet = mIFpDevDriver.getTemplateByImg(sImage1, sImage2, sImage3);
            if (arrRet[0].equals("0")) {
                speak("指纹采集成功");
                OttoManager.getInstance().deliverMsg(OttoMsg.OTTO_COLLECT_FINGER_SUCESS, arrRet[1]);
            }
            return;
        }
    }

    public void match(final String fingerTemplate) {
        g_bIsCancel = false;
        tz = "";
        new Thread() {
            public void run() {
                byte[] szCurImageBuf = new byte[IMAGE_LEN_BASE64];
                int iTimeOut = 0;
                int dwImageLen = 0;
                long lStartTime, lEndTime;
                String[] arrRet;
                if (sDeviceID.equals("")) {
                    speak("未获取设备ID");
                    return;
                }
                // 循环集指纹图像，直到采集到合格图像
                lStartTime = System.currentTimeMillis();
                iTimeOut = 15;
                while (true) {
                    // 检测手指是否按下 (可以通过FPICheckFinger来检测是否按手指，然后再采集图像)
                    // 是否取消
                    if (g_bIsCancel) {
                        speak("操作取消");
                        return;
                    }
                    // 判定时间
                    lEndTime = System.currentTimeMillis();
                    if ((lEndTime - lStartTime) >= iTimeOut * 1000) {
                        speak("验证超时");
                        return;
                    }

                    arrRet = mIFpDevDriver.checkFinger();
                    if (arrRet[0].equals("0")) {
                        break;
                    }
                }
                // 取指纹图像
                arrRet = mIFpDevDriver.getImageEx(sDeviceID, sRandom, sBmpFile);
                if (!arrRet[0].equals("0")) {
                    tz = "";
                    return;
                }
                arrRet = mIFpDevDriver.getImageEx(sDeviceID, sRandom, sBmpFile);
                if (!arrRet[0].equals("0")) {
                    speak("验证失败");
                    OttoManager.getInstance().deliverMsg(OttoMsg.OTTO_MACTH_FINGER_FAILE, null);
                    return;
                }
                dwImageLen = Integer.parseInt(arrRet[2]);
                System.arraycopy(arrRet[1].getBytes(), 0, szCurImageBuf, 0, dwImageLen);
                // 生成指纹特征
                arrRet = mIFpDevDriver.getFeatureByImg(szCurImageBuf);
                if (arrRet[0].equals("0")) {
                    tz = arrRet[1].trim();
                }
                arrRet = mIFpDevDriver.fpVerify(fingerTemplate, tz, 3);
                if (!arrRet[0].equals("0")) {
                    speak("验证失败");
                    OttoManager.getInstance().deliverMsg(OttoMsg.OTTO_MACTH_FINGER_FAILE, null);
                    return;
                } else {
                    OttoManager.getInstance().deliverMsg(OttoMsg.OTTO_MACTH_FINGER_SUCESS, null);
                }
            }

            ;
        }.start();
    }

    public void speak(String mess) {
        Speaker_.getInstance_(GoodBoxManagerApp_.getInstance()).speak(mess);
    }

    public void e(String s) {
        Log.e("FingerHandler", s);
    }
}